package cn.edu.jsu.zjj.controller;


import cn.edu.jsu.zjj.annotation.AuthCheck;
import cn.edu.jsu.zjj.annotation.Type;
import cn.edu.jsu.zjj.common.DeleteRequest;
import cn.edu.jsu.zjj.common.result.PageResult;
import cn.edu.jsu.zjj.common.result.Result;
import cn.edu.jsu.zjj.config.JwtProperties;
import cn.edu.jsu.zjj.constant.JwtClaimsConstant;
import cn.edu.jsu.zjj.constant.MessageConstant;
import cn.edu.jsu.zjj.constant.UserConstant;
import cn.edu.jsu.zjj.exception.BaseException;
import cn.edu.jsu.zjj.exception.ThrowUtils;
import cn.edu.jsu.zjj.model.dto.docu.DocuAddMyRequest;
import cn.edu.jsu.zjj.model.dto.docu.DocuQueryRequest;
import cn.edu.jsu.zjj.model.dto.docu.DocuUpdateMyRequest;
import cn.edu.jsu.zjj.model.entity.*;
import cn.edu.jsu.zjj.model.utils.ImportUtils;
import cn.edu.jsu.zjj.model.utils.JwtUtil;
import cn.edu.jsu.zjj.service.*;
import cn.hutool.json.JSONUtil;
import cn.zhxu.bs.BeanSearcher;
import cn.zhxu.bs.util.MapUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import io.jsonwebtoken.Claims;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import kotlin.Pair;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 资料相关接口
 */
@CrossOrigin
@RestController
@RequestMapping("/docu")
@Api(tags = "资料相关接口")
@Slf4j
public class DocuController {
    @Autowired
    private DocuService docuService;
    @Autowired
    private UserService userService;
    @Autowired
    private AyService ayService;
    @Autowired
    private ISysHeaderService sysHeaderService;
    @Autowired
    private ISysDataService dataService;
    @Autowired
    private BeanSearcher beanSearcher;
    @Autowired
    private JwtProperties jwtProperties;
    @Autowired
    private ISysDataService sysDataService;




    @ApiOperation("导入资料")
    @PostMapping("/import")
    public Result<String> importExcel(@RequestParam("file") MultipartFile[] file,HttpServletRequest request) {
        if (file == null) {
            return Result.error("文件不能为空");
        }
        Long majorId = userService.getLoginUser().getMajorId();
        String token = request.getHeader(jwtProperties.getTokenName());
        Claims claims = JwtUtil.parseJWT(jwtProperties.getSecretKey(), token);
        Long userId = Long.valueOf(claims.get(JwtClaimsConstant.USER_ID).toString());
        String userName = userService.getOne(new QueryWrapper<User>().eq("id" , userId).eq("is_delete", 0)).getName();

        for (MultipartFile f : file) {
            if (f.isEmpty()) {
                return Result.error("文件不能为空");
            }
            Pair<List<String>, List<List<String>>> pair = ImportUtils.importExcel(f);
            String fileName = f.getOriginalFilename();

            //保存资料
            Docu docu = new Docu();
            docu.setUserId(userId);
            docu.setOperName(userName);
            docu.setName(fileName);
            docu.setStatus("1");
            docu.setCreateTime(LocalDateTime.now());
            docu.setUpdateTime(LocalDateTime.now());
            docu.setIsDelete(0);
            docu.setMajorId(majorId);
            docu.setEndTime(Date.from(LocalDate.now().plusDays(30).atStartOfDay().toInstant(ZoneOffset.of("+8"))));
            //TODO:后续可能需要设置学年学期，暂时先不设置
            docuService.save(docu);

            List<String> headerList = pair.getFirst();
            List<List<String>> dataList = pair.getSecond();
            // 校验表头，数据是否为空
            if (headerList == null || dataList == null) {
                return Result.error("请上传正确的Excel文件，表头和数据不能为空");
            }
            //不为空，导出表头和数据
            //先保存表头,排除最后一个附件列
            for (int i = 0; i < headerList.size()-1; i++) {
                SysHeader sysHeader = new SysHeader();
                sysHeader.setName(headerList.get(i));
                sysHeader.setSort(i);
                sysHeader.setDocuId(docu.getId());
                int j = i+1;
                sysHeader.setHeaderKey("key" + j);
                sysHeader.setUserId(userId);
                sysHeader.setCreateTime(LocalDateTime.now());
                sysHeader.setUpdateTime(LocalDateTime.now());
                sysHeader.setIsDelete(0);
                sysHeader.setUserName(userName);
                sysHeaderService.save(sysHeader);
            }
            //再保存数据
            Map<String, String> map = new HashMap<>();
            //没有专业列的情况
            for(List<String> data : dataList){
                for(int i = data.size()-2; i >= 0; i--){
                    int j = i+1;
                    //保存数据为map，key为headerKey，value为data
                    map.put("key" + j, data.get(i));
                }
                String mapJson = JSONUtil.toJsonStr(map);
                SysData sysData = new SysData();
                sysData.setDocuId(docu.getId());
                sysData.setData(mapJson);
                sysData.setCreateTime(LocalDateTime.now());
                sysData.setUpdateTime(LocalDateTime.now());
                sysData.setUserId(userId);
                sysData.setIsDelete(0);
                sysData.setUserName(userName);
                dataService.save(sysData);
            }
//            //有专业列的情况
//            if(Objects.equals(headerList.size(), dataList.size()) && Objects.equals(headerList.get(headerList.size()-1), "专业")){
//                int indexOf = headerList.indexOf("专业");
//                for(List<String> data : dataList){
//                    for(int i = data.size()-2; i >= 0; i--){
//                        int j = i+1;
//                        //保存数据为map，key为headerKey，value为data
//                        map.put("key" + j, data.get(i));
//                    }
//                    String mapJson = JSONUtil.toJsonStr(map);
//                    SysData sysData = new SysData();
//                    sysData.setDocuId(docu.getId());
//                    sysData.setData(mapJson);
//                    sysData.setCreateTime(LocalDateTime.now());
//                    sysData.setUpdateTime(LocalDateTime.now());
//                    sysData.setUserId(userId);
//                    sysData.setIsDelete(0);
//                    sysData.setUserName(userName);
//                    dataService.save(sysData);
//                }
//            }
        }


        return Result.success("导入成功");
    }

    @ApiOperation("资料导出，表头一样就合并表格，不一样就分目录导出多个文件")
    @PostMapping("/exports")
    public void exportMulti(@ModelAttribute DocuQueryRequest docuQueryRequest, HttpServletResponse response) throws IOException {


        Long userMajorId = userService.getLoginUser().getMajorId();
        List<Long> ids = new ArrayList<>();
        // 判断是否选择了资料
        if(!Objects.equals(docuQueryRequest.getIds(), null)){
            //选择了
            ids = docuQueryRequest.getIds();

        }else{
            // ids为空，没其他条件，导出全部
            if(Objects.isNull(docuQueryRequest.getName()) && Objects.isNull(docuQueryRequest.getOperName()) && Objects.isNull(docuQueryRequest.getStatus()) && Objects.isNull(docuQueryRequest.getTerm())){
                ids = docuService.list(new LambdaQueryWrapper<Docu>().eq(Docu::getIsDelete, 0).eq(Docu::getMajorId, userMajorId)).stream().map(Docu::getId).collect(Collectors.toList());
            }else {
                //ids为空，选择了其他条件，导出筛选资料
                ids = beanSearcher.search(Docu.class,
                        MapUtils.builder()
                                .field(Docu::getName, docuQueryRequest.getName()).op("la")
                                .field(Docu::getOperName, docuQueryRequest.getOperName()).op("ct")
                                .field(Docu::getIsDelete, 0)
                                .field(Docu::getCreateTime, docuQueryRequest.getCreateTime()).op("ge")
                                .field(Docu::getEndTime, docuQueryRequest.getEndTime()).op("le")
                                .field(Docu::getStatus, docuQueryRequest.getStatus())
                                .field(Docu::getMajorId, userMajorId).op("like")
                                .field(Docu::getTerm, docuQueryRequest.getTerm())
                                .orderBy("createTime", "desc")
                                .build()).getDataList().stream().map(Docu::getId).collect(Collectors.toList());
            }
        }
        docuQueryRequest.setIds(ids);
        dataService.exportMulti(docuQueryRequest,response);

    }

//
//    @ApiOperation("多资料导出")
//    @PostMapping("/export")
//    public Result<String> exportExcel(@RequestParam List<Long> ids, HttpServletResponse response) throws IOException {
//        List<SysHeader> headers = sysHeaderService.list(new LambdaQueryWrapper<SysHeader>().in(SysHeader::getDocuId, ids).ne(SysHeader::getIsDelete, 1));
//        List<SysData> dataList = dataService.list(new LambdaQueryWrapper<SysData>().in(SysData::getDocuId, ids).ne(SysData::getIsDelete, 1));
//        List<List<String>> headerList = new ArrayList<>();
//        List<List<Object>> dataLists = new ArrayList<>();
//
//        // 获取去重的表头
//        List<String> newHeaderList = headers.stream().map(SysHeader::getName).distinct().collect(Collectors.toList());
//
//        int size = headers.size() / 2;
//        if (newHeaderList.size() != size) {
//            throw new BaseException(MessageConstant.FILE_HEADER_NOT_SAME);
//        }
//
//        // 遍历表头，添加到headerList中
//        for (String header : newHeaderList) {
//            ArrayList<String> headerInfo = new ArrayList<>();
//            headerInfo.add(header);
//            headerList.add(headerInfo);
//        }
//        headerList.add(new ArrayList<String>() {{
//            add("附件");
//        }});
//
//        // 遍历数据，添加到dataLists中
//        for (SysData data : dataList) {
//            JSONObject jsonObject = JSONUtil.parseObj(data.getData());
//            List<Object> dataInfo = new ArrayList<>();
//            for (Map.Entry<String, Object> entry : jsonObject.entrySet()) {
//                dataInfo.add(entry.getValue());
//            }
//            dataInfo.add(data.getFileName());
//            dataLists.add(dataInfo);
//        }
//
//        // Remove duplicates and keep track of removed items
//        Set<List<Object>> seen = new HashSet<>();
//        List<List<Object>> removedDataList = new ArrayList<>();
//        List<List<Object>> uniqueDataList = new ArrayList<>();
//
//        for (List<Object> dataInfo : dataLists) {
//            if (!seen.add(dataInfo)) {
//                removedDataList.add(dataInfo);
//            } else {
//                uniqueDataList.add(dataInfo);
//            }
//        }
//
//        // Export the unique data list
//        ExcelUtils.export(response, headerList, uniqueDataList, removedDataList);
//        return Result.success("资料合并导出成功");
//    }
//
//
//    @ApiOperation("资料选中导出")
//    @PostMapping("/zip")
//    public void exportZip(@ModelAttribute DocuQueryRequest docuQueryRequest,@RequestBody List<Long> ids, HttpServletResponse response) throws IOException {
//        long page = docuQueryRequest.getCurrent() - 1;
//        int size = docuQueryRequest.getPageSize();
//        List<ZipVo> zipVoList = new ArrayList<>();
//        List<Docu> docuList = new ArrayList<>();
//        if(ids.isEmpty()){
//            docuList = beanSearcher.search(Docu.class,
//                    MapUtils.builder()
//                            .field(Docu::getName, docuQueryRequest.getName()).op("ct")
//                            .field(Docu::getOperName, docuQueryRequest.getOperName()).op("ct")
//                            .field(Docu::getIsDelete, 0)
//                            .field(Docu::getCreateTime, docuQueryRequest.getCreateTime()).op("ge")
//                            .field(Docu::getEndTime, docuQueryRequest.getEndTime()).op("le")
//                            .field(Docu::getStatus, docuQueryRequest.getStatus())
//                            .field(Docu::getTerm, docuQueryRequest.getTerm())
//                            .page(page, size)
//                            .orderBy("createTime", "desc") // 使用 orderBy 方法按创建时间降序排序
//                            .build()).getDataList();
//        }else{
//            docuList = docuService.list(new LambdaQueryWrapper<Docu> ().in(Docu::getId, ids).ne(Docu::getIsDelete, 1));
//        }
//        // 判断是否过期
//        for (Docu docu : docuList) {
//            if(docu.getEndTime().before(Date.from(LocalDate.now().plusDays(1).atStartOfDay().toInstant(ZoneOffset.of("+8"))))){
//                docu.setStatus("0");
//                docuService.updateById(docu);
//            }
//        }
//        // 获取ID列表
//        List<Long> docuIds = docuList.stream().map(Docu::getId).collect(Collectors.toList());
//
//        for (Long id : docuIds) {
//            List<SysHeader> headers = sysHeaderService.list(new LambdaQueryWrapper<SysHeader>()
//                    .eq(SysHeader::getDocuId, id)
//                    .orderByAsc(SysHeader::getSort));
//            List<String> headList = new ArrayList<>();
//            List<String> sortList = new ArrayList<>();
//            for (SysHeader header : headers) {
//                headList.add(header.getName());
//                sortList.add(header.getHeaderKey());
//            }
//            //TODO: 添加附件列
//            headList.add("附件名称");
//            List<List<Object>> dataList = new ArrayList<>();
//
//            List<String> userRoleList = userService.getLoginUser().getRoles();
//
//
//            // 获取动态数据
//            LambdaQueryWrapper<SysData> queryWrapper1 = new LambdaQueryWrapper<SysData>();
//            queryWrapper1.eq(SysData::getDocuId, id);
//            queryWrapper1.ne(SysData::getIsDelete, 1);
//            // 教师角色，只能查看自己的资料
//            if (userRoleList.contains("user")) {
//                queryWrapper1.eq(SysData::getUserId, userService.getLoginUser().getId());
//            }
//            List<SysData> sysDataList = sysDataService.list(queryWrapper1);
//
//            //文件名，二进制数组的键值对
//            List<String> fileNameList = new ArrayList<>();
//            List<byte[]> bytesList = new ArrayList<>();
//
//            for (SysData sysData : sysDataList) {
//                JSONObject jsonObject = JSONUtil.parseObj(sysData.getData());
//                List<Object> objectList = new ArrayList<>();
//
//                for (String sort : sortList) {
//                    boolean found = false;
//                    for (Map.Entry<String, Object> entry : jsonObject.entrySet()) {
//                        if (Objects.equals(entry.getKey(), sort)) {
//                            objectList.add(entry.getValue());
//                            found = true;
//                            break; // 找到后跳出内层循环
//                        }
//                    }
//                    if (!found) {
//                        objectList.add(null); // 如果没有找到对应的 key，添加 null
//                    }
//                }
//
//                objectList.add(sysData.getFileName());
//                dataList.add(objectList);
//
//                // 附件
//                String fileUrl = sysData.getFileUrl();
//                if (StringUtils.isNotEmpty(fileUrl)) {
//                    ZipUtils.urlToByte(sysData.getFileUrl());
//                    fileNameList.add(ZipUtils.fileName);
//                    bytesList.add(ZipUtils.urlBytes);
//                }
//            }
//
//
//
//
//            // 将文件名和二进制数组的键值对封装成Pair对象
//            Pair<List<String>, List<byte[]>> pair = new Pair<>(fileNameList, bytesList);
//
//            LambdaQueryWrapper<Docu> docuQueryWrapper = new LambdaQueryWrapper<>();
//            docuQueryWrapper.eq(Docu::getId, id);
//            Docu docu = docuService.getOne(docuQueryWrapper);
//            String excelName = docu.getName();
//            // 调用工具类进行导出
//            ZipVo zipVo = new ZipVo();
//            zipVo.setHeaders(headList);
//            zipVo.setData(dataList);
//            zipVo.setPair(pair);
//            zipVo.setExcelName(excelName);
//            zipVoList.add(zipVo);
//        }
//        ZipUtils.totalMain(response, zipVoList);
//    }
//

        @ApiOperation("资料分页查询和导出")
        @PostMapping("/page")
        public Result page(@RequestBody DocuQueryRequest docuQueryRequest) {
            long page = docuQueryRequest.getCurrent() - 1;
            int size = docuQueryRequest.getPageSize();

            // 获取当前登录用户的 majorId
            Long userMajorId = userService.getLoginUser().getMajorId();

            // 调用服务层方法进行查询
            List<Docu> docuList = beanSearcher.search(Docu.class,
                    MapUtils.builder()
                            .field(Docu::getName, docuQueryRequest.getName()).op("la")
                            .field(Docu::getOperName, docuQueryRequest.getOperName()).op("ct")
                            .field(Docu::getIsDelete, 0)
                            .field(Docu::getCreateTime, docuQueryRequest.getCreateTime()).op("ge")
                            .field(Docu::getEndTime, docuQueryRequest.getEndTime()).op("le")
                            .field(Docu::getStatus, docuQueryRequest.getStatus())
                            .field(Docu::getTerm, docuQueryRequest.getTerm())
                            .field(Docu::getMajorId, userMajorId).op("like")
                            .page(page, size)
                            .orderBy("createTime", "desc")
                            .build()).getDataList();

            for (Docu docu : docuList) {
                if (docu.getEndTime().before(Date.from(LocalDate.now().plusDays(1).atStartOfDay().toInstant(ZoneOffset.of("+8"))))) {
                    docu.setStatus("0");
                    docuService.updateById(docu);
                }
            }
            return Result.success(new PageResult(docuList.size(), docuList));
        }

        @ApiOperation("分页获取当前用户创建的资料列表")
        @PostMapping("/page/my")
        public Result pageMy(@RequestBody DocuQueryRequest docuQueryRequest, HttpServletRequest request) {
            String token = request.getHeader(jwtProperties.getTokenName());
            Claims claims = JwtUtil.parseJWT(jwtProperties.getSecretKey(), token);
            Long userId = Long.valueOf(claims.get(JwtClaimsConstant.USER_ID).toString());
            long page = docuQueryRequest.getCurrent() - 1;
            int size = docuQueryRequest.getPageSize();

            // 获取当前登录用户的 majorId
            Long userMajorId = userService.getLoginUser().getMajorId();

            // 调用服务层方法进行查询
            List<Docu> docuList = beanSearcher.search(Docu.class,
                    MapUtils.builder()
                            .field(Docu::getUserId, userId)
                            .field(Docu::getName, docuQueryRequest.getName()).op("ct")
                            .field(Docu::getOperName, docuQueryRequest.getOperName()).op("ct")
                            .field(Docu::getIsDelete, 0)
                            .field(Docu::getCreateTime, docuQueryRequest.getCreateTime()).op("ge")
                            .field(Docu::getEndTime, docuQueryRequest.getEndTime()).op("le")
                            .field(Docu::getStatus, docuQueryRequest.getStatus())
                            .field(Docu::getMajorId, userMajorId).op("like")
                            .page(page, size)
                            .build()).getDataList();

            return Result.success(new PageResult(docuList.size(), docuList));
        }


    /**
     * 新增资料
     *
     * @param docuAddMyRequest
     * @return
     */
    @ApiOperation("新增资料（仅管理员）")
    @PostMapping
    @AuthCheck(mustRoles = {UserConstant.ADMIN_ROLE, UserConstant.EDU_ADMIN_ROLE, UserConstant.MAJOR_ADMIN_ROLE})
    public Result save(@RequestBody DocuAddMyRequest docuAddMyRequest) {
        log.info("新增资料：{}", docuAddMyRequest);
        if (docuAddMyRequest.getEndTime() == null) {
            throw new BaseException(MessageConstant.PARAMS_ERROR);
        }
        Docu docu = new Docu();
        BeanUtils.copyProperties(docuAddMyRequest, docu);
        docu.setOperName(userService.getLoginUser().getName());
        docu.setUserId(userService.getLoginUser().getId());
        docu.setCreateTime(LocalDateTime.now());
        docu.setIsDelete(0);
        if(docu.getEndTime().before(Date.from(LocalDate.now().plusDays(1).atStartOfDay().toInstant(ZoneOffset.of("+8"))))){
            throw new BaseException(MessageConstant.TIME_SELECT_ERROR);
        }
        //获取当前学年,判断当前时间在哪个学年区间
        LambdaQueryWrapper<Ay> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.ge(Ay::getEndTime, new Date());
        queryWrapper.le(Ay::getCreateTime, new Date());
        Ay ay = ayService.getOne(queryWrapper);
        if (ay != null) {
            docu.setTerm(ay.getTerm());
        }
        boolean result = docuService.save(docu);
        ThrowUtils.throwIf(!result, MessageConstant.OPERATION_ERROR);
        return Result.success();
    }

    /**
     * 编辑资料信息
     * @param docuUpdateMyRequest
     * @return
     */
    @Type("编辑资料信息")
    @ApiOperation("编辑资料信息")
    @PutMapping
    public Result update(@RequestBody DocuUpdateMyRequest docuUpdateMyRequest) {
        log.info("编辑资料，请求体为：{}", docuUpdateMyRequest);
        if (docuUpdateMyRequest == null) {
            throw new BaseException(MessageConstant.PARAMS_ERROR);
        }
        Docu docu = docuService.getById(docuUpdateMyRequest.getId());
        if(docuUpdateMyRequest.getEndTime() == null && docu.getEndTime().before(Date.from(LocalDate.now().plusDays(1).atStartOfDay().toInstant(ZoneOffset.of("+8"))))){
            return Result.error(MessageConstant.TIME_END);
        }
        BeanUtils.copyProperties(docuUpdateMyRequest, docu);
        docu.setOperName(userService.getById(docu.getUserId()).getName());
        docu.setUserId(docu.getUserId());
        docu.setUpdateTime(LocalDateTime.now());
        boolean result = docuService.updateById(docu);
        ThrowUtils.throwIf(!result, MessageConstant.OPERATION_ERROR);
        return Result.success();
    }

    /**
     * 删除资料
     * @param deleteRequest
     * @return
     */
    @Type("删除资料")
    @PostMapping("/delete")
    @ApiOperation("删除资料")
//    public Result deleteUser(@RequestBody DeleteRequest deleteRequest) {
//        log.info("删除资料：{}", deleteRequest);
//        if (deleteRequest == null || deleteRequest.getId() <= 0) {
//            throw new BaseException(MessageConstant.PARAMS_ERROR);
//        }
//        boolean b = docuService.removeById(deleteRequest.getId());
//        return Result.success(b);
//    }
    public Result deleteDouc(@RequestBody DeleteRequest deleteRequest) {
        log.info("删除资料：{}", deleteRequest);
        if (deleteRequest == null || deleteRequest.getId() <= 0) {
            return Result.error(MessageConstant.PARAMS_ERROR);
        }
        return Result.success(docuService.removeById(deleteRequest.getId()));
    }

    /**
     * 根据id查询资料
     *
     * @param id
     * @return
     */
    @ApiOperation("根据id查询资料")
    @GetMapping("/{id}")
    public Result getById(@PathVariable Long id) {
        if (id <= 0) {
            throw new BaseException(MessageConstant.PARAMS_ERROR);
        }
        Docu docu = docuService.getById(id);
        return Result.success(docu);
    }


//    public FileOutputStream downloadZipFile(Long signId) throws Exception {
//        InputStream input = null;
//        //  定义压缩输出流
//        ZipOutputStream zipOut = null;
//        File zipFile = null;
//        List<String> ossList = null;
//        String path = null;
//        String download = null;
//        String localPath = null;
//        try {
//            ossList = new ArrayList();
//            // 根据signId查询签署文档
//            List<Docu> signDocuments = docuService.list();
//            // 如果不为空
//            if (!signDocuments.isEmpty()) {
//                // 如果只有一个签署文件就直接下载,如果有多个就打压缩包
//                if (signDocuments.size()==1) {
//                    return downloadDetails(signId);
//                }else{
//                    for (Docu signDocument : signDocuments) {
//                        // 根据签署文档的attachId查询对应的附件
//                        Attach attach = dataService.(signDocument.getId());
//                        String link = attach.getLink();
//                        // 把oss文件下载到项目本地
//                        path = DocuController.class.getClass().getResource("/").getPath() +
//                                FileUtil.getNameWithoutExtension(link) + ".xls";
//                        localPath = SignDocumentServiceImpl.class.getClass().getResource("/").getPath();
//                        // 把获取到的oss文件链接下载到本地
//                        download = download(link, path);
//                        ossList.add(download);
//                        //  定义压缩文件夹的名称和相关的位置
//                        zipFile = new File(localPath + "file.zip");
//                        //  实例化压缩输出流  并定制压缩文件的输出路径
//                        zipOut = new ZipOutputStream(new FileOutputStream(zipFile));
//                    }
//                }
//            }
//            for (String o : ossList) {
//                File file = new File(o);
//                //  定义输入文件流
//                input = new FileInputStream(file);
//                // 一个文件对对应一个ZipEntry实体
//                zipOut.putNextEntry(new ZipEntry(file.getName()));
//                int readsize = 1024 * 1024 * 5;
//                byte[] buf = new byte[readsize];
//                int temp = 0;
//                while ((temp = input.read(buf)) != -1) {
//                    zipOut.write(buf, 0, temp);
//                }
//            }
//            //  删除本地文件
//            // FileUtil.deleteQuietly(new File(path));
//        } catch (IOException e) {
//            log.error("打包下载失败！", e);
//        } finally {
//            if(null != zipOut){
//                zipOut.closeEntry();
//                zipOut.close();
//            }
//            if(null != input){
//                input.close();
//            }
//            // 回收资源
//            System.gc();
//        }
//        // 压缩包文件转为FileOutputStream
//        FileOutputStream fileOutputStream = new FileOutputStream(String.valueOf(zipOut));
//        return fileOutputStream;
//    }
//
//
//    private FileOutputStream downloadDetails(Long signId) throws Exception {
//        String path = null;
//        String download = null;
//        FileOutputStream fileOutputStream = null;
//        // 根据signId查询签署文档
//        List<SignDocumentVO> signDocuments = signDocumentMapper.selectAttachs(signId);
//        // 如果不为空
//        if (!signDocuments.isEmpty()) {
//            for (SignDocument signDocument : signDocuments) {
//                // 根据签署文档的attachId查询对应的附件
//                Attach attach = attachMapper.selectAttachById(signDocument.getAttachId());
//                String link = attach.getLink();
//                // 把oss文件下载到项目本地
//                path = SignDocumentServiceImpl.class.getClass().getResource("/").getPath() +
//                        FileUtil.getNameWithoutExtension(link) + "." + PDF;
//                // 把获取到的oss文件链接下载到本地
//                download = download(link, path);
//                File file = new File(download);
//                fileOutputStream = new FileOutputStream(file);
//            }
//        }
//        return fileOutputStream;
//    }
}
